<!-- Page header -->
<div class="page-header d-print-none">
  <div class="container-xl">
    <div class="row g-2 align-items-center">
      <div class="col">
        <!-- Page pre-title -->
        <!-- <div class="page-pretitle">
          子标题
        </div> -->
        <h2 class="page-title" id="article_list_board_title">
          <!-- 如果是版块页面，那么文字替换成版块名 -->
          首页
        </h2>
        <!-- 帖子数量 -->
        <div class="text-muted mt-1" id="article_list_count_board"></div>
      </div>
      <!-- Page title actions -->
      <div class="col-auto ms-auto d-print-none">
        <div class="btn-list">
          <!-- 发新帖按钮 宽屏 -->
          <a href="javascript:void(0);" class="btn btn-primary d-none d-sm-inline-block article_post">
            <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24"
              stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
              <path stroke="none" d="M0 0h24v24H0z" fill="none" />
              <path d="M12 5l0 14" />
              <path d="M5 12l14 0" />
            </svg>
            发布帖子
          </a>
          <!-- 发新帖按钮 窄屏 -->
          <a href="javascript:void(0);" class="btn btn-primary d-sm-none btn-icon article_post" aria-label="发布帖子">
            <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24"
              stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
              <path stroke="none" d="M0 0h24v24H0z" fill="none" />
              <path d="M12 5l0 14" />
              <path d="M5 12l14 0" />
            </svg>
          </a>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- Page body -->
<div class="page-body">
  <div class="container-xl">
    <div class="row justify-content-center">
      <div class="col-12">
        <div class="card">
          <!-- 修改card-body为flex布局 -->
          <div class="card-body d-flex flex-column" style="min-height: 60vh;">
            <!-- 内容区域自动填充 -->
            <div class="flex-fill">
              <div class="divide-y" id="artical-items-body">
                <!-- 动态生成帖子列表 -->
              </div>
            </div>

            <!-- 分页控件会自动推到最下方 -->
            <div class="mt-auto pt-3">
              <!-- 分页代码放在这里 -->
              <div class="d-flex justify-content-center">
                <nav aria-label="Page navigation">
                  <ul class="pagination mb-0" id="pagination-controls">
                    <li class="page-item disabled" id="prev-page">
                      <a class="page-link" href="javascript:void(0)" onclick="changePage(currentPage - 1)">
                        &laquo; 上一页
                      </a>
                    </li>

                    <li class="page-item active">
                      <a class="page-link" href="javascript:void(0)">
                        第 <span id="current-page">1</span> 页 / 共 <span id="total-pages">1</span> 页
                      </a>
                    </li>

                    <li class="page-item" id="next-page">
                      <a class="page-link" href="javascript:void(0)" onclick="changePage(currentPage + 1)">
                        下一页 &raquo;
                      </a>
                    </li>
                  </ul>
                </nav>
              </div>

              <!-- 页码跳转输入框 -->
              <div class="d-flex justify-content-center mt-2">
                <div class="input-group" style="max-width: 250px;">
                  <input type="number" class="form-control" id="page-input" min="1" value="1" placeholder="输入页码"
                    aria-label="页码">
                  <button class="btn btn-outline-primary" type="button" onclick="jumpToPage()">
                    跳转
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<script>

  $(function () {
    // ========================= 分页状态管理 =======================
    currentPage = 1;
    totalPages = 1;
    totalItems = 0;
    pageSize = 5; // 每页显示数量
    let currentBoardId = null;

    // ========================= 初始化函数 =======================
    function init() {
      initPaginationEvents();
      loadArticles();
    }

    // ========================= 初始化分页事件 =======================
    function initPaginationEvents() {
      // 绑定回车键事件
      $('#page-input').on('keypress', function (e) {
        if (e.key === 'Enter') {
          jumpToPage();
        }
      });

      // 初始化分页控件状态
      updatePaginationControls();
    }

    // ========================= 切换页面 =======================
    window.changePage = function (page) {
      if (page < 1 || page > totalPages || page === currentPage) {
        return;
      }
      currentPage = page;
      loadArticles();
    }

    // ========================= 跳转到指定页 =======================
    window.jumpToPage = function () {
      const input = $('#page-input');
      let page = parseInt(input.val());

      if (isNaN(page) || page < 1) {
        page = 1;
      } else if (page > totalPages) {
        page = totalPages;
      }

      input.val(page);
      changePage(page);
    }

    // ========================= 更新分页控件状态 =======================
    function updatePaginationControls() {
      $('#current-page').text(currentPage);
      $('#total-pages').text(totalPages);

      $('#page-input').val(currentPage).attr('max', totalPages);

      // 更新按钮状态
      $('#prev-page').toggleClass('disabled', currentPage === 1);
      $('#next-page').toggleClass('disabled', currentPage === totalPages);

      // 显示总条目数信息（可选）
      $('#article_list_count_board').html(`帖子数量: ${totalItems} (第 ${currentPage}/${totalPages} 页)`);
    }

    // ========================= 获取帖子列表 =======================
    function loadArticles() {
      // 获取当前选中的版块
      let activeLiEl = $('#topBoardList>.active');
      let queryString = `?page=${currentPage}&size=${pageSize}`;
      currentBoardId = null;

      // 导航栏版块Item是否绑定版块数据
      let boardData = activeLiEl.data('board');
      if (boardData) {
        queryString += '&boardId=' + boardData.id;
        currentBoardId = boardData.id;
        getBoardInfo(boardData.id);
      } else {
        $('#article_list_board_title').html('首页');
        $('#article_list_count_board').show();
      }

      // 显示加载状态
      showLoading();

      $.ajax({
        type: 'get',
        url: 'article/getAllByBoardId' + queryString,
        success: function (respData) {
          if (respData.code == 0) {
            processArticleData(respData.data);
          } else {
            showError('加载失败: ' + respData.message);
            $.toast({
              heading: '警告',
              text: respData.message,
              icon: 'warning'
            });
          }
        },
        error: function () {
          showError('网络错误，请重试');
          $.toast({
            heading: '错误',
            text: '访问出现问题，请与管理员联系.',
            icon: 'error'
          });
        }
      });
    }

    // ========================= 处理文章数据 =======================
    function processArticleData(data) {
      if (!data) {
        showError('数据格式错误');
        return;
      }
      console.log(data)
      // 解析分页信息和文章列表
      const articles = data.content || data.list || data;
      const pageInfo = data.page || data;

      // 更新分页状态
      if (pageInfo) {
        currentPage = pageInfo.currentPage || pageInfo.pageNumber || pageInfo.page || currentPage;
        totalPages = pageInfo.totalPages || pageInfo.totalPage || Math.ceil((pageInfo.totalCount || pageInfo.totalElements || articles.length) / pageSize) || 1;
        totalItems = pageInfo.totalCount || pageInfo.totalElements || articles.length;
      }

      // 构建帖子列表
      listBuildArticleList(articles);
      updatePaginationControls();
    }

    // ========================= 获取版块信息 =======================
    function getBoardInfo(boardId) {
      if (!boardId) return;

      $.ajax({
        type: 'get',
        url: 'board/getById?id=' + boardId,
        success: function (respData) {
          if (respData.code == 0) {
            let board = respData.data;
            $('#article_list_board_title').html(board.name);
            $('#article_list_count_board').show();
          }
        }
      });
    }

    // ========================= 构造帖子列表 =======================
    function listBuildArticleList(data) {
      if (!data || data.length == 0) {
        $('#artical-items-body').html('<div class="text-center py-5 text-muted">暂无帖子</div>');
        return;
      }

      $('#artical-items-body').empty();
      let avatarUrl = 'image/avatar01.jpeg';

      // 确保全局变量存在
      window.currentArticle = window.currentArticle || null;

      data.forEach(article => {
        if (!article.user.avatarUrl) {
          article.user.avatarUrl = avatarUrl;
        }

        // ... [保持原有的HTML字符串不变] ...
        let articleHtmlStr = `
                <div class="article-item mb-3">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <span class="avatar" style="background-image: url(${article.user.avatarUrl})"></span>
                        </div>
                        <div class="col">
                            <div class="text-truncate">
                                <a href="javascript:void(0);" class="article_list_a_title text-decoration-none">
                                    <strong>${article.title || '无标题'}</strong>
                                </a>
                            </div>
                            <div class="text-muted mt-2">
                                <div class="row align-items-center">
                                    <div class="col">
                                        <ul class="list-inline list-inline-dots mb-0">
                                            <li class="list-inline-item">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-user" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                                                    <path d="M12 7m-4 0a4 4 0 1 0 8 0a4 4 0 1 0 -8 0"></path>
                                                    <path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"></path>
                                                </svg>
                                                ${article.user.nickname || '匿名用户'}
                                            </li>
                                            <li class="list-inline-item">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clock" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                                                    <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path>
                                                    <path d="M12 7v5l3 3"></path>
                                                </svg>
                                                ${article.createTime || ''}
                                            </li>
                                        </ul>
                                    </div>
                                    <div class="col-auto">
                                        <ul class="list-inline list-inline-dots mb-0">
                                            <li class="list-inline-item" title="浏览数">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-eye" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                                                    <path d="M12 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"></path>
                                                    <path d="M22 12c-2.667 4.667 -6 7 -10 7s-7.333 -2.333 -10 -7c2.667 -4.667 6 -7 10 -7s7.333 2.333 10 7"></path>
                                                </svg>
                                                ${article.visitCount || 0}
                                            </li>
                                            <li class="list-inline-item" title="点赞数">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-heart" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                                                    <path d="M19.5 12.572l-7.5 7.428l-7.5 -7.428a5 5 0 1 1 7.5 -6.566a5 5 0 1 1 7.5 6.572"></path>
                                                </svg>
                                                ${article.likeCount || 0}
                                            </li>
                                            <li class="list-inline-item" title="回复数">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-message-circle" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                                                    <path d="M3 20l1.3 -3.9a9 8 0 1 1 3.4 2.9l-4.7 1"></path>
                                                </svg>
                                                ${article.replyCount || 0}
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        let articleItem = $(articleHtmlStr);
        let articleTitle = articleItem.find('.article_list_a_title');

        articleTitle.click(function () {
          // 直接设置当前文章并跳转
          currentArticle = article;

          // 移除导航激活状态（如果函数存在）
          if (window.removeNavActive) {
            window.removeNavActive();
          }

          // 加载详情页面
          if ($('#bit-forum-content').length) {
            $('#bit-forum-content').load('details.html', function () {
              // 页面加载完成后，可以在这里触发详情渲染
              console.log('详情页面加载完成', currentArticle);

              // 如果details.html中有渲染函数，可以在这里调用
              if (window.renderArticleDetails && currentArticle) {
                window.renderArticleDetails(currentArticle);
              }
            });
          }

          // 阻止默认行为（如果有的话）
          return false;
        });

        $('#artical-items-body').append(articleItem);
      });
    }

    // ========================= 辅助函数 =======================
    function showLoading() {
      $('#artical-items-body').html(`
            <div class="text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2 text-muted">加载中...</p>
            </div>
        `);
    }

    function showError(message) {
      $('#artical-items-body').html(`
            <div class="text-center py-5 text-danger">
                <i class="fas fa-exclamation-triangle me-2"></i>
                ${message}
            </div>
        `);
    }

    // ========================= 重新加载函数（供外部调用） =======================
    window.reloadArticles = function () {
      currentPage = 1;
      loadArticles();
    }

    // ========================= 初始化执行 =======================
    init();
  });

  // ================== 处理发贴事件 =====================
  $('.article_post').click(function () {
    console.log('加载发贴页面');
    removeNavActive();
    $('#bit-forum-content').load('article.html');
  });
</script>